package com.heima.wemedia.interceptor;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.utils.WmThreadLocalUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Package: com.heima.wemedia.interceptor
 * ClassName: WmTokenInterceptor
 * Description:
 *
 * @Author : 福森森
 * @Create : 2024/8/27 11:12
 */
public class WmTokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断请求是否来自网关，如果不是，响应400
        String requestHeader = request.getHeader("X-Request-From");
        if (!StrUtil.equals(requestHeader, "heima-leadnews-wemedia-gateway")) {
            response.setStatus(HttpStatus.HTTP_BAD_REQUEST);
            return false;
        }
        //得到header中的信息
        String userId = request.getHeader("userId");
        if (StrUtil.isNotEmpty(userId)) {
            //把用户存入threadlocal中
            WmUser wmUser = new WmUser();
            wmUser.setId(Convert.toInt(userId));
            WmThreadLocalUtil.setUser(wmUser);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        WmThreadLocalUtil.clear();
    }
}
